package com.dayu;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;

import com.dayu.finecomm.aop.AopProxy;
import com.dayu.finecomm.service.FCService;
import com.dayu.finecomm.source.CollectSource;

@Controller
public class Application implements ApplicationContextAware, InitializingBean {

	private ApplicationContext context;

	@Value(value = "${service.finecomm.enabled:false}")
	private boolean finecommEnabled;

	@Autowired
	FCService finecomm;

	@Autowired
	AopProxy aopProxy;

	@Resource
	CollectSource stations;

	private final ExecutorService pool = Executors.newCachedThreadPool();

	public void run(ApplicationContext ctx) {

		if (finecommEnabled) {
			getPool().submit(finecomm);
		}
	}

	public static void main(String[] args) throws InterruptedException {

		ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:/context-unitalk.xml");

		Application app = ctx.getBean(Application.class);
		// 启动应用
		app.run(ctx);

		app.getPool().awaitTermination(2 * 36500, TimeUnit.DAYS);

		System.out.println("Exiting...");

		ctx.close();
	}

	public ExecutorService getPool() {
		return pool;
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.context = applicationContext;
	}

	@Override
	public void afterPropertiesSet() throws Exception {

		aopProxy.setApplicationContext(this.context);
		this.run(this.context);
	}
}
